import {Component, OnInit} from '@angular/core';
import {BasePage} from '../../common/basePage';
import {Events, NavController, ToastController} from '@ionic/angular';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute} from '@angular/router';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {thousandTimesValidator} from '../../common/validators';
import {ConfigService} from '../../services/config.service';
import {AppConfig} from '../../common/app-config.enum';

@Component({
  selector: 'app-loan-apply',
  templateUrl: './loan-apply.page.html',
  styleUrls: ['./loan-apply.page.scss'],
})
export class LoanApplyPage extends BasePage implements OnInit {

  formModel: FormGroup;
  type: any;
  // 产品相关参数
  product: any = {};
  // 申请数据
  bid: any;
  // 金额上下限提示
  amountPlaceholder: string;
  // 期限选项列表
  periodList: any[] = [];
  // 筹款时间选项列表
  investPeriodList: any[] = [7, 8, 9, 10];
  // 还款方式
  repaymentType: any[] = [];
  // 借款用途和描述最小字数限制
  minLength = {
    purpose: 10,
    description: 20
  };

  constructor(
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    public configService: ConfigService,
    private fb: FormBuilder,
    private routeInfo: ActivatedRoute,
    private events: Events,
    private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
    this.formModel = fb.group({
      amount: [null, [Validators.required]],
      period: ['', [Validators.required]],
      investPeriod: [null, [Validators.required]],
      repaymentType: ['', [Validators.required]],
      purpose: ['', [Validators.required, Validators.minLength(this.minLength.purpose)]],
      description: ['', [Validators.required, Validators.minLength(this.minLength.description)]]
    });
  }

  ngOnInit() {
    this.type = this.routeInfo.snapshot.params;
    this.service$.doRequest(UrlAndOPT.loan_apply, {productId: this.type['id']})
      .subscribe(obj => {
        if (obj) {
          this.product = obj['obj']['product']; // 获取产品信息
          this.bid = obj['obj']['bid']; // 获取申请信息
          // 获取金额上下限
          this.amountPlaceholder = this.product['min_amount'] + '元~' + this.product['max_amount'] + '元';
          // 增加金额上下限验证
          this.formModel.get('amount').setValidators([
            // thousandTimesValidator, // 借款金额必须为1000的整数倍
            Validators.min(this.product['min_amount']),
            Validators.max(this.product['max_amount'])
          ]);
          // 获取期限列表
          for (let i = this.product['min_period']; i < this.product['max_period'] + 1; i++) {
            this.periodList.push({
              val: i,
              txt: i + (this.product['period_unit'] === 'MONTH' ? '个月' : '天')
            });
          }
          // 获取还款方式
          this.repaymentType = this.product['repayment_type'].split(',');
          if (this.bid) { // 如果为修改申请，读取申请信息
            const repaymentTypeList: any[] = this.product['productRepaymentTypeList'];
            this.formModel.patchValue({
              amount: this.bid['amount'],
              period: this.bid['period'],
              investPeriod: this.bid['invest_period'],
              repaymentType: this.repaymentType[repaymentTypeList.indexOf(this.bid['repayment_type'])],
              purpose: this.bid['purpose'],
              description: this.bid['description'],
            });
          }
        }
      });
  }

  // 提交申请
  doApply() {
    if (this.formModel.valid) {
      const params = {
        ...this.formModel.value,
        productId: this.type['id'] || this.product['id']
      };
      this.service$.doRequest(UrlAndOPT.loan_apply_submit, params)
        .subscribe(obj => {
          if (obj) {
            this.events.publish(AppConfig.TOPIC_UNDO_LIST);
            this.showToast('提交申请成功！');
            this.navCtrl.pop()
              .then(() => {
                this.navCtrl.navigateForward(['/auth/loan-upload', {userRole: 2}]); // 前往上传资料页面
              });
          }
        });
    } else {
      this.showToast(
        this.getErrorMessage()
      ).catch(() => {});
    }
  }

  // 获取错误信息
  private getErrorMessage() {
    const errorMsg = '请完善资料';
    if (this.formModel.getError('min', ['amount']) || this.formModel.getError('max', ['amount'])) {
      return '金额限制' + this.amountPlaceholder;
    }
    console.log(this.formModel.get(['purpose']));
    if (this.formModel.getError('minlength', ['purpose'])) {
      return '借款用途不得少于' + this.minLength.purpose + '个字';
    }
    if (this.formModel.getError('minlength', ['description'])) {
      return '借款描述不得少于' + this.minLength.description + '个字';
    }
    return errorMsg;
  }

}
